package cc.fathervideoplayer

import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream


fun Context.getCacheList(key: String): MutableList<File>? {
    val file = File(getExternalFilesDir(null), key)
    return runCatching { ObjectInputStream(FileInputStream(file)).readObject() as MutableList<File> }
        .getOrElse {
            Toast.makeText(this, "无缓存", Toast.LENGTH_SHORT).show()
            null
        }
}

fun startScanAll(context: Context, key: String, block: (MutableList<File>) -> Unit) {
    GlobalScope.launch {
        val list = mutableListOf<File>()
        val sdcard = File("/storage/0000-0000")
        //扫描内部存储
        scanVideo(Environment.getExternalStorageDirectory(), list, block)
        //扫描sdcard
        scanVideo(sdcard, list, block)
        Log.d(TAG, "startScan: finish")
        context.saveCache(list, key)
        withContext(Dispatchers.Main) {
            Toast.makeText(context, "扫描结束", Toast.LENGTH_SHORT).show()
        }
    }
}

fun startScan(
    context: Context,
    key: String,
    files: MutableList<File>,
    block: (MutableList<File>) -> Unit,
) {
    GlobalScope.launch {
        val list = mutableListOf<File>()
        for (f in files) {
            scanVideo(f, list, block)
        }
        Log.d(TAG, "startScan: finish")
        list.sortBy { -it.lastModified() }
        context.saveCache(list, key)
        withContext(Dispatchers.Main) {
            Toast.makeText(context, "扫描结束", Toast.LENGTH_SHORT).show()
        }
    }
}

suspend fun scanAll(
    files: MutableList<File>,
): MutableList<File> {
    val list = mutableListOf<File>()
    for (f in files) {
        scanVideo(f, list, {})
    }
    return list
    Log.d(TAG, "startScan: finish")
}

fun Context.saveCache(list: MutableList<File>, key: String, async: Boolean = false) {
    fun write() {
        val file = File(getExternalFilesDir(null), key)
        ObjectOutputStream(FileOutputStream(file)).writeObject(list)
    }
    if (async) {
        GlobalScope.launch { write() }
    } else {
        write()
    }
}

private const val TAG = "Com"
private suspend fun scanVideo(
    file: File,
    list: MutableList<File>,
    block: (MutableList<File>) -> Unit,
) {
    if (file.isFile) {
        Log.d(TAG, "scanVideo: $file")
        file.name.also {
            if (it.endsWith(".mp4", true) || it.endsWith(".flv", true) || it.endsWith(
                    ".mkv",
                    true
                ) || it.endsWith(".avi", true) || it.endsWith(".3pg", true) || it.endsWith(
                    ".m4a",
                    true
                )
            ) {
                list.add(file)
                Log.v(TAG, "scanVideo: find video!$file")
                withContext(Dispatchers.Main) {
                    block.invoke(list)
                }
            }
        }
    } else {
        file.listFiles()?.forEach {
            scanVideo(it, list, block)
        }
    }
}

fun File.getFileNameWithoutExt(): String {
    val pointIndex = name.lastIndexOf('.')
    if (pointIndex < 0) {
        return name
    }
    return name.substring(0, pointIndex)
}

fun File.playVideo(context: Context) {
    val intent = Intent(context, PlayActivity::class.java)
//    val c = context.contentResolver.query(
//        MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
//        arrayOf(MediaStore.Video.VideoColumns._ID),
//        "${MediaStore.Video.VideoColumns.DATA}=?",
//        arrayOf(absolutePath),
//        null
//    )
//    c?.use {
//        val id = it.getLong(0)
//        val uri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
//    }
    intent.putExtra("path", absolutePath)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
}